package robato.util;

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.Canvas;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JFrame;

public class CaptureScreen extends Canvas{
	private static final long serialVersionUID = -8613421198713396409L;
	
	Robot myRobot;
	Rectangle screenRectangle;
	BufferedImage screenImage;
	JFrame myFrame;
	String strDir;
	
	public CaptureScreen(){
		try {
			this.myRobot=new Robot();
		} catch (AWTException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public CaptureScreen(JFrame frame, String strName){
		
		try{
			this.myFrame = frame;
			this.strDir = strName;
 			this.myRobot=new Robot();
 			this.screenRectangle=new Rectangle(frame.getBounds());
 			this.myFrame.update(this.myFrame.getGraphics());
 			//this.update(this.myFrame.getGraphics());
 			this.screenImage=myRobot.createScreenCapture(this.screenRectangle);
 			this.myFrame=new JFrame("Capture Screen");
 			this.myFrame.add(this);
 			this.myFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
 			this.myFrame.setSize(frame.getSize());
 			this.myFrame.setVisible(true);

 			File outputfile = new File(strName+".png");
 			ImageIO.write(screenImage, "png", outputfile);
 			Runtime r = Runtime.getRuntime();
 			r.gc();

		}
		catch(Exception exception){
 			exception.printStackTrace();
		}
	}
	
	public void setParameters(JFrame frame, String strName){
		this.myFrame = frame;
		this.strDir = strName;
		
	}
	
	public void capture(){	
		this.myFrame.update(this.myFrame.getGraphics());
		this.screenRectangle=new Rectangle(this.myFrame.getBounds());
		this.screenImage=this.myRobot.createScreenCapture(this.screenRectangle);
		File outputfile = new File(this.strDir+".png");
		try {
			ImageIO.write(screenImage, "png", outputfile);
		} catch (IOException e) {e.printStackTrace();}
	}

	public void paint(Graphics g)	{
		g.drawImage(screenImage,0,0,this);
	}

	public static void main(String[]args){
		JFrame frame = new JFrame();
		frame.setSize(Toolkit.getDefaultToolkit().getScreenSize());
		new CaptureScreen(frame, "c://robots/HolaMundo");
	}
}
